package main

import (
	"github.com/gin-contrib/cors"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/redis"
	"github.com/gin-gonic/gin"
	"github.com/webook/internal/repository"
	"github.com/webook/internal/repository/dao"
	"github.com/webook/internal/service"
	"github.com/webook/internal/web"
	"github.com/webook/internal/web/middlewares"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"strings"
	"time"
)

func main() {
	db := initDB()
	server := initWebServer()
	initUserHdl(db, server)

	err := server.Run(":8080")
	if err != nil {
		return
	}
}

func initUserHdl(db *gorm.DB, server *gin.Engine) {
	ud := dao.NewUserDao(db)
	ur := repository.NewUserRepository(ud)
	us := service.NewUserService(ur)
	hdl := web.NewUserHandler(us)
	hdl.RegisterRoutes(server)
}

func initDB() *gorm.DB {
	db, err := gorm.Open(mysql.Open("root:root@tcp(localhost:13316)/webook"))
	if err != nil {
		panic("数据库连接故障" + err.Error())
	}
	err = dao.InitTables(db)
	if err != nil {
		panic(err)
	}
	return db
}

func initWebServer() *gin.Engine {
	server := gin.Default()

	server.Use(cors.New(cors.Config{
		AllowCredentials: true,
		//AllowAllOrigins: true,
		//AllowOrigins: []string{"http://localhost:3000"},
		AllowHeaders: []string{"Content-Type", "Authorization"},
		//允许前端访问你的后端响应中访问你的后端
		ExposeHeaders: []string{"x-jwt-token"},
		AllowOriginFunc: func(origin string) bool {
			if strings.Contains(origin, "http://localhost") {
				return true
			}
			if strings.Contains(origin, "http://127.0.0.1") {
				return true
			}
			return strings.Contains(origin, "your_company.com")
		},
		MaxAge: 12 * time.Hour,
	}), func(ctx *gin.Context) {
		println("这是我的Middlerware")
	})
	//userSession(server)
	userJWT(server)
	return server
}

func userJWT(server *gin.Engine) {
	login := middlewares.LoginJWTMiddlwareBuilDer{}
	server.Use(login.CheckLogin())
}

func userSession(server *gin.Engine) {
	login := &middlewares.LoginMiddlwareBuilDer{}
	//存储数据的，也就是userId存哪里
	//store := cookie.NewStore([]byte("secret"))
	//基于内存的实现
	//store := memstore.NewStore([]byte("qK1=vJ9[qS4|dW9,lQ7|cS3_qU6#eE6_"),
	//	[]byte("pT8/tX3(tD9-pG2@wA9]iS9;zE6[sP8?"))
	store, err := redis.NewStore(16, "tcp", "localhost:6379", "",
		[]byte("qK1=vJ9[qS4|dW9,lQ7|cS3_qU6#eE6_"), []byte("pT8/tX3(tD9-pG2@wA9]iS9;zE6[sP8?"))
	if err != nil {
		panic(err)
	}
	server.Use(sessions.Sessions("ssid", store), login.CheckLogin())
}
